//
//  HMNetworkTools.swift
//  Swift网络请求封装
//
//  Created by HM on 16/9/20.
//  Copyright © 2016年 HM. All rights reserved.
//

import UIKit
import AFNetworking

//  网络请求类型
enum RequestType: Int {
    // get请求
    case GET
    // post请求
    case POST
}

//  网络请求封装类
class HMNetworkTools: AFHTTPSessionManager {
    
    //  单例全局访问点
    static let sharedTools: HMNetworkTools = {
        let tools = HMNetworkTools()
        //  添加可以接受的响应数据类型
        tools.responseSerializer.acceptableContentTypes?.insert("text/html")
        tools.responseSerializer.acceptableContentTypes?.insert("text/plain")
        return tools
        
    }()
    
    //  封装get/post请求
    fileprivate func request(type: RequestType, url: String, params: Any?, callBack: @escaping (Any?, Error?)->()) {
        
        if type == .GET {
            get(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response, nil)
                }, failure: { (_, error) in
                    callBack(nil, error)
            })
            
        } else {
            post(url, parameters: params, progress: nil, success: { (_, response) in
                callBack(response, nil)
                }, failure: { (_, error) in
                    callBack(nil, error)
            })
            
        }
        
    }
}

//发微博相关接口
extension HMNetworkTools {
    //图文微博
    func upload(accessToken: String, status: String, image: UIImage, callBack:@escaping(Any?,Error?)->()) {
        //url
        let url = "https://upload.api.weibo.com/2/statuses/upload.json"
        //参数
        let params = [
            "access_token": accessToken,
            "status": status,
            
        ]
        //图片转为二进制
        //let imageData = UIImagePNGRepresentation(image)!
        //compressionQuality 质量系数 0-1 越大质量越高,越清晰
        let imageData = UIImageJPEGRepresentation(image, 0.5)!
        //保存桌面查看效果
//        (imageData as NSData).write(toFile: "/Users/apple/Desktop/1.jpg", atomically: true)
//        post(url, parameters: params, constructingBodyWith: { (formData) in
//            //withFileData 图片的二进制数据
//            //name: 服务端参数
//            //fileName: 图片文件名->客户端可以随便填
//            //mimeType: 图片资源类型
//            formData.appendPart(withFileData: imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
//            }, progress: nil, success: { (_, response) in
//                callBack(response,nil)
//            }) { (_, error) in
//                callBack(nil,error)
//        }
        //发送请求
        post(url, parameters: params, constructingBodyWith: { (formdata) in
            formdata.appendPart(withFileData: imageData, name: "pic", fileName: "test", mimeType: "image/jpeg")
            }, progress: nil, success: { (_, response) in
                callBack(response,nil)
            }) { (_, error) in
                callBack(nil,error)
        }
    }
    //文字微博
    func update(accessToken: String, status: String, callBack:@escaping(Any?,Error?)->()) {
        //url
        let url = "https://api.weibo.com/2/statuses/update.json"
        //参数
        let params = [
            "access_token": accessToken,
            "status": status
        ]
        //执行请求
        request(type: .POST, url: url, params: params, callBack: callBack)
    }
}

//微博首页相关接口
extension HMNetworkTools {
    func requestStatuses(accessToken: String, maxId: Int64, sinceId: Int64, callBack:@escaping(Any?,Error?)->()) {
        //准备接口地址
        let url = "https://api.weibo.com/2/statuses/friends_timeline.json"
        //准备参数
        let params: [String: Any] = [
            "access_token": accessToken,
            "max_id": maxId,
            "since_id": sinceId
        ] as [String : Any]
        //拼接get请求Url
        print("-----------------------")
        print(url+"?access_token=\(accessToken)")
        print("-----------------------")
        //执行接口请求
        request(type: .GET, url: url, params: params, callBack: callBack)
    }
}

// OAuth登录相关接口
extension HMNetworkTools {
    //根据AccessToken获取用户信息
    func requestUserInfo(accessToken: String, uid: Int64, callBack:@escaping(Any?,Error?)->()) {
        //请求接口地址
        let url = "https://api.weibo.com/2/users/show.json"
        //准备请求参数
        let params = [
            "access_token": accessToken,
            "uid": uid
        ] as [String : Any]
        request(type: .GET, url: url, params: params, callBack: callBack)
    }
    // 根据code获取accessToken
    func requestAccessToken(code: String, callBack:@escaping(Any?,Error?)->()) {
        //请求接口地址
        let url = "https://api.weibo.com/oauth2/access_token"
        let params = [
            "client_id": WeiBoAppKey,
            "client_secret": WeiboAppSecret,
            "grant_type": "authorization_code",
            "code": code,
            "redirect_uri": WeiBoRedirect_URI
        ]
        request(type: .POST, url: url, params: params, callBack: callBack)
    }
}


